package io.renren.modules.app.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.app.entity.VehicleEntity;
import io.renren.modules.app.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

/**
 * @Auther zxl
 * @Date 2019/1/3 23:44
 * @Description 阿里云行驶证识别参数配置
 **/
@ConfigurationProperties(prefix = "aliyun.vehicle-ocr")
@Component
public class VehicleOCRConfig {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String host;
    private String path;
    private String appcode;

    private String appKey;
    private String appSecret;

    /*
     * 获取参数的json对象
     */
    public static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }


    /**
     * 驾驶证识别
     * @param imgFile
     * @param side
     * @return
     */
    public R ocrImg(String imgFile, String side){

        System.out.println("into ocr -------");

        // 如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        Boolean is_old_format = false;
        JSONObject configObj = new JSONObject();
        configObj.put("side", side);
        String config_str = configObj.toString();
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        // 对图像进行base64编码
        String imgBase64 = "";
        try {
            File file = new File(imgFile);
            byte[] content = new byte[(int) file.length()];
            FileInputStream finputstream = new FileInputStream(file);
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
            logger.info("图片编码完成:"+imgBase64);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException("图片编码异常");
        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if(is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if(config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            }else{
                requestObj.put("image", imgBase64);
                if(config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();
        try {
            logger.info("行驶证解析请求发送。。。。"+System.currentTimeMillis());
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            logger.info("行驶证解析请求获取成功。。。。"+System.currentTimeMillis());
            if(stat != 200){
                logger.error("阿里云行驶证识别API调用异常，Http code: "+stat
                        +",Http body error msg:"+EntityUtils.toString(response.getEntity()));
                return R.error(stat,EntityUtils.toString(response.getEntity()));
            }
            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);
            System.out.println(res_obj.toJSONString());
            VehicleEntity vehicleEntity = JSON.parseObject(res_obj.toJSONString(), VehicleEntity.class);

            System.out.println(vehicleEntity.toString());
            return R.ok().put("data",vehicleEntity);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error(500,"未知异常");
    }





    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getAppcode() {
        return appcode;
    }

    public void setAppcode(String appcode) {
        this.appcode = appcode;
    }

    public String getAppKey() {
        return appKey;
    }

    public void setAppKey(String appKey) {
        this.appKey = appKey;
    }

    public String getAppSecret() {
        return appSecret;
    }

    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }
}
